package cn.bonoon.kernel.io;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class StorageMultipartRequest extends StorageFile{

	private final MultipartHttpServletRequest multipartRequest;
	
	/** 如果没有定义要读取的文件名，则会读取{@link #multipartRequest}下的所有已经上传的文件 */
	private final String[] filenames;
	
	/** 同一个名称下，是否有多个文件 */
	private boolean multiValue = false;//多文件上传时要设置为true
	
	StorageMultipartRequest(Object catalog, MultipartHttpServletRequest multipartRequest, String...filenames) {
		super(catalog);
		this.multipartRequest = multipartRequest;
		this.filenames = filenames;
	}
	
	StorageMultipartRequest(Object catalog, HttpServletRequest request, String...filenames) {
		this(catalog, (MultipartHttpServletRequest)request, filenames);
	}

	public void setMultiValue(boolean multiValue) {
		this.multiValue = multiValue;
	}
	
	@Override
	public MultipartFile[] getSourceFile() {
		List<MultipartFile> mfs = new ArrayList<>();
		if(null != filenames && filenames.length > 0){
			for(String fn : filenames){
				if(multiValue){
					mfs.addAll(multipartRequest.getFiles(fn));
				}else{
					mfs.add(multipartRequest.getFile(fn));
				}
			}
		}else{
			//读出所有的文件
			if(multiValue){
				for(List<MultipartFile> amf : multipartRequest.getMultiFileMap().values()){
					mfs.addAll(amf);
				}
			}else{
				mfs.addAll(multipartRequest.getFileMap().values());
			}
		}
		return mfs.toArray(new MultipartFile[mfs.size()]);
	}
}
